import express, { Application } from 'express';
import bodyParse from 'body-parser';
import { fileOperation, readFile, writeFile } from './utils';
import { ITodoData } from '../src/js/typing';

const app: Application = express();

app.use(bodyParse.urlencoded({ extended: true }));
app.use(bodyParse.json());


app.all('*', (req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header('Access-Control-Allow-methods','POST,GET,PUT,DELELTE,OPTIONS');
    next();
});

app.get('/todolist', (req, res) => {
    const todolist: string = fileOperation('todo.json') as string;
    res.send(todolist);
});

app.post('/toggle', (req, res)=> {
    const id: number = parseInt(req.body.id);
    
    fileOperation('todo.json', (todoList: ITodoData[]) => {
        return todoList.map((todo: ITodoData) => {
            if(todo.id === id) {
                todo.completed = !todo.completed
            }
            return todo;
        })
    })

    res.send({
        msg: 'ok',
        statusCode: 200
    })
});

app.post('/remove', (req, res)=> {
    const id: number = parseInt(req.body.id);

    fileOperation('todo.json', (todoList: ITodoData[]) => {
        console.log(todoList);
        return todoList.filter((todo:ITodoData) => todo.id !== id);
    })

    res.send({
        msg: 'ok',
        statusCode: 200
    })
});

app.post('/add', (req, res)=> {
    const todo: string = req.body.todo;
    
    fileOperation('todo.json', (todoList: ITodoData[]) => {
        todoList.push(JSON.parse(todo));
        return todoList;
    })

    res.send({
        msg: 'ok',
        statusCode: 200
    })
});

app.listen(8080, () => {
    console.log('Welcome to EXPRESS');
    console.log('8080 is running');
})
